import Framework from './framework'
import Util from './util.js'
import Formatter from './formatter.js'
import Proxy from './proxy'
import Services from './services'
import Config from '../config.js'
import QmPlus from './qmplus'
import RePlus from './replus'

export default {
    install(Vue, Framework7) {
        this.polyfill(Framework7)
        const framework = Services.getInstance(
            'framework',
            Framework,
            Framework7
        )
        Util.$f7 = Framework7
        Vue.prototype.$db = framework.db
        Vue.prototype.$framework = framework
        Vue.prototype.$util = Util
        Vue.prototype.$formatter = Formatter

        window.qmplus = QmPlus

        // html5plus初始化准备
        Util.plusReady(() => {
            this.plusReady(Framework7, framework)
        })

        //Run Job
        Object.keys(framework.jobs).forEach((key) => {
            if (framework.jobs[key].anonymous === true) {
                framework.jobs[key].register()
            }
        })
    },
    plusReady(app, framework) {
        // 需要plus初始化完成触发plusready事件后才能拿到plus对象
        var h5plus = window.plus ? window.plus : {}

        // 做一些扩展，如果有重复的变量定义方法定义等，h5plus会覆盖QmPlus
        var appPlus = Util.merge(QmPlus, h5plus, RePlus)

        // 使用扩展的plus对象
        window.qmplus = appPlus

        // this.initCustomSplashScreen()

        // 判断iOS系统是否是暗黑模式，从而改变app主题
        if (window.qmplus.isIOS()) {
            this.adjustDarkTheme(framework)
            this.uistylechangeListen(framework)
        }

        this.backbuttonListen(app, framework)
        this.initDownloader()
    },
    // 重写个别F7的api
    polyfill(app) {
        ;(app.dialog.alert = (message, title, callbackOk) => {
            if (title !== String) {
                callbackOk = title
                title = null
            }
            vue.$dialog
                .alert({
                    message: message,
                    title: title || '温馨提示',
                    className: 'dialogzindex',
                    overlayClass: 'overlayzindex',
                    confirmButtonColor: '#1677FF',
                    getContainer() {
                        return document.querySelector('.framework7-root')
                    },
                })
                .then(callbackOk)
        }),
            (app.dialog.confirm = (
                message,
                title,
                callbackOk,
                callbackCancel
            ) => {
                // 只处理的确定事件，如果有确定和取消按钮事件需要写上title
                if (title !== String) {
                    callbackOk = title
                    title = null
                }

                vue.$dialog
                    .confirm({
                        message: message,
                        title: title || '温馨提示',
                        className: 'dialogzindex',
                        overlayClass: 'overlayzindex',
                        confirmButtonColor: '#1677FF',
                        getContainer() {
                            return document.querySelector('.framework7-root')
                        },
                    })
                    .then(callbackOk)
                    .catch(callbackCancel)
            }),
            (app.dialog.toast = function (text, closeTimeout) {
                if (!closeTimeout) closeTimeout = 3000
                var withToolbar = false
                try {
                    withToolbar = app.views.current.$el
                        .find('.page-current')
                        .hasClass('with-views-toolbar')
                } catch (e) {
                    withToolbar = false
                }
                var temp = app.toast.create({
                    text: text,
                    closeTimeout: closeTimeout,
                    cssClass: withToolbar ? 'toast-auto' : '',
                })
                temp.open()
            })
        app.request.setup({
            timeout: 15000,
            beforeCreate(options) {
                Proxy.encode(options)
                if (Util.isProd()) {
                    Proxy.map(options)
                }
            },
            beforeSend: function (xhr, options) {
                if (app.data.authToken) {
                    xhr.setRequestHeader(
                        'championsoftTokenAuthorization',
                        `championsoft ${app.data.authToken}`
                    )
                }
                if (app.data.csrfToken) {
                    xhr.setRequestHeader('X-CSRF-TOKEN', app.data.csrfToken)
                }
            },
            // 2.x版本用
            // response: function (xhr, result) {
            //     console.log(xhr);
            //     if (xhr.responseURL && xhr.responseURL.endsWith("/login")) {
            //         app.preloader.hide();
            //         app.router.navigate(Config.api.login);
            //     }
            //     Proxy.decode(xhr, result);
            // },
            // 4.x版本用
            error: function error(xhr) {
                // console.log(xhr);
            },
            complete: function complete(xhr) {
                // 不管请求成功与否都会调用complete
                // console.log(xhr);
                if (
                    xhr &&
                    xhr.responseURL &&
                    xhr.responseURL.endsWith('/login') &&
                    !xhr.responseURL.endsWith('/api/base/account/login') &&
                    !xhr.responseURL.endsWith('/mobileApi/base/account/login')
                ) {
                    app.preloader.hide()
                    app.views.main.router.navigate(Config.pages.login)
                }
            },
            success: function (result, status, xhr) {
                // console.log(xhr);
                // if (xhr.responseURL && xhr.responseURL.endsWith("/login")
                //     && !xhr.responseURL.endsWith("/api/base/account/login")
                //     && !xhr.responseURL.endsWith("/mobileApi/base/account/login")) {
                //     app.preloader.hide();
                //     app.views.main.router.navigate(Config.api.login);
                // }
                Proxy.decode(xhr, result)
            },
        })
    },

    // 判断iOS系统是否是暗黑模式，从而改变app主题
    adjustDarkTheme(framework) {
        if (window.qmplus.navigator.getUiStyle) {
            var style = window.qmplus.navigator.getUiStyle()
            if ('dark' == style) {
                framework.theme.setLayoutTheme('dark')
            }
        } else {
            console.log('当前sdk无法获取系统UI')
        }
    },

    // 返回事件监听
    backbuttonListen(app, framework) {
        var backCount = 0
        localStorage.setItem('backbutton1', 'backbutton1')
        window.qmplus.key.addEventListener(
            'backbutton',
            (e) => {
                framework.viewer.close()
                localStorage.setItem('backbutton2', 'backbutton2')
                // if (window.plus) {
                //     let wv = window.plus.webview.getDisplayWebview()[0]
                //     localStorage.setItem('wv', wv)
                //     localStorage.setItem(
                //         'currentWebview',
                //         window.plus.webview.currentWebview()
                //     )
                //     if (wv != window.plus.webview.currentWebview()) {
                //         wv.canBack((r) => {
                //             if (r.canBack) {
                //                 wv.back()
                //             } else if (wv.preloading) {
                //                 wv.hide('slide-out-bottom')
                //             } else {
                //                 wv.close('slide-out-bottom')
                //             }
                //         })
                //         return
                //     } else if ('qualityWindow' == wv.id) {
                //         wv.canBack((r) => {
                //             if (r.canBack) {
                //                 wv.back()
                //             } else {
                //                 window.plus.webview.currentWebview().close()
                //             }
                //         })
                //     }
                // }
                if (window.scan && window.scan.isClose === false) {
                    window.scan.close()
                    app.views.current.router.back()
                    return
                }

                var dialog = app.dialog.get()
                if (dialog) {
                    dialog.close()
                    return
                }

                var searchbar = app.searchbar.get()
                if (searchbar && searchbar.enabled) {
                    searchbar.disable()
                    return
                }

                var sheet = app.sheet.get()
                if (sheet) {
                    sheet.close()
                    return
                }

                var actions = app.actions.get()
                if (actions) {
                    actions.close()
                    return
                }

                var popover = app.popover.get()
                if (popover) {
                    popover.close()
                    return
                }

                var picker = app.picker.get()
                if (picker && picker.opened) {
                    picker.close()
                    return
                }

                var popup = app.popup.get()
                if (popup) {
                    popup.close()
                    return
                }

                if (
                    app.views.current.router.url == framework.config.pages.login
                ) {
                    framework.redirect.home()
                    return
                }

                var smartSelect = app.smartSelect.get()
                if (smartSelect && smartSelect.opened) {
                    smartSelect.close()
                    return
                }

                if (vue.vantToBeClosed && vue.vantToBeClosed.length > 0) {
                    let pop = vue.vantToBeClosed.pop()

                    pop.close && pop.close()
                    return
                }

                if (
                    app.views.current.router.url != framework.config.pages.home
                ) {
                    backCount = 0
                    window.setTimeout(function () {
                        app.views.current.router.back()
                    }, 50)
                } else {
                    backCount++
                }

                if (backCount == 1) {
                    app.dialog.toast('再按一次退出程序')
                }

                if (backCount > 1) {
                    app.dialog.confirm('确定退出程序吗？', function (r) {
                        if (r) {
                            window.plus.runtime.quit()
                        }
                    })
                }
                //framework.update.check();
                //			if($(".popup-sendWorkflow").hasClass('modal-in')) {
                //				//弹出工作流审批表单时，点击系统菜单返回按钮，关闭审批页面
                //				$(".close-popup").click();
                //				return;
                //			}
            },
            false
        )
    },

    // 系统主题改变监听
    uistylechangeListen(framework) {
        // 监听系统UI改变
        document.addEventListener(
            'uistylechange',
            function () {
                if (window.qmplus.navigator.getUiStyle) {
                    var style = window.qmplus.navigator.getUiStyle()
                    if ('dark' == style) {
                        framework.theme.setLayoutTheme('dark')
                    }
                } else {
                    console.log('当前sdk无法获取系统UI')
                }
            },
            false
        )
    },

    // 初始化下载器
    initDownloader() {
        // 枚举所有状态（-1）的下载任务列表
        window.qmplus.downloader.enumerate(function (tasks) {
            Util.each(tasks, (task) => {
                vue.$f7.data.downloaders.push({
                    url: task.url,
                    name: task.filename.substr(
                        task.filename.lastIndexOf('/') + 1
                    ),
                    state: task.state === undefined ? 4 : task.state,
                    task: task,
                })
            })
        }, -1)
    },

    // 自定义启动图操作逻辑
    // initCustomSplashScreen() {
    //     // 先关掉启动图
    //     window.qmplus.navigator.closeSplashscreen()
    // },
}
